//logs.js
var util = require('../../utils/util.js');
var app = getApp();
Page({
  //定义初始化数据  每当数据发生变化时，会自动触发页面循环
  data: {
    img: 'img/111.png',
    introduce: 'false',
    inputValue: '',
    returnValue: '',
    allContentList: [],
    key: "5a703aea44000069b2c21b07", //奇智机器人key
    num: 0,
    userInfo: {}
  },
  //绑定键盘按下事件，讲输入的值赋给data
  bindKeyInput: function (e) {



    this.setData({
      inputValue: e.detail.value
    })

  },

  //robot introduce触发事件
  changeIntroduce: function (e) {
    let that = this;
    let introduce = that.data.introduce
    if (introduce == 'false') {
      that.setData({
        introduce: 'true'
      })
    }
    else {
      that.setData({
        introduce: 'false'
      })
    }
  },

  //点击发送按钮时触发事件，发送数据给奇智机器人
  submitTo: function (e) {

    let that = this;

    
    that.setData({
      img: 'img/222.png'
    })
    setTimeout(
      function () {
        
        that.setData({
          img: 'img/111.png'
        });
      }
      , 250);


    if (that.data.inputValue != '' && that.data.inputValue != ' ') {

      //将输入数据追加到列表里面
      that.data.allContentList.push({ "value": that.data.inputValue });
      

      //奇智接口
      let _url = 'https://api.chatbot.cn/cloud/robot/5a703aea44000069b2c21b07/answer'; 
      //系统封装的请求方法 ，注意这里没有ajax的说法
      wx.request({
        url: _url,
        method:'GET',
        data: {
          key: that.data.key,
          question: that.data.inputValue
        },
        //封装返回数据格式
        header: {
          'Content-Type': 'application/json'
        },
        //请求成功的回调
        success: function (res) {
          //控制台
          console.log(res.data);
          console.log(res.data.answers);
          console.log(res.data.answers[0].respond);
          
          
          
          let data = res.data;
          if (data.answers!=='') {   //100000 表示返回成功
            //将返回值追加到列表
            that.data.allContentList.push({ "value": data.answers[0].respond});
            //调用set方法，告诉系统数据已经改变   启动循环，循环聊天信息
            that.setData({
              returnValue: data.answers,
              allContentList: that.data.allContentList
            })
            
            //底部对齐
            {
              wx.createSelectorQuery().select('.containerBox').boundingClientRect(function (rect) {
                // 使页面滚动到底部
                wx.pageScrollTo({
                  scrollTop: rect.height
                })
              }).exec()

            }


          } else {

          }

        }
      })
      //清空input框
      this.setData({
        inputTemp: "",

      })

    }
    //清空inputValue
    that.data.inputValue = '';

  },




  onLoad: function () {
    console.log('onLoad')
    var that = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function (userInfo) {
      //更新数据
      that.setData({
        userInfo: userInfo
      })
    })
  }

})
